<script setup lang="ts">
import { reactive } from 'vue';
import { useBoolean } from '@sa/hooks';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import Title from '@/components/common/login/auth-title.vue';
import InputPassword from '@/components/advanced/input-password/input-password.vue';

defineOptions({
  name: 'Register'
});

interface Emit {
  (event: 'changeModule', module: UnionKey.LoginModule): void;
}
const emit = defineEmits<Emit>();

const { formRef, validate } = useNaiveForm();
const { bool: loading, setBool: setLoading } = useBoolean();

interface FormModel {
  userPhone: string;
  password: string;
  confirmPassword: string;
  agreePolicy: string;
}

const model: FormModel = reactive({
  userPhone: '',
  password: '',
  confirmPassword: '',
  agreePolicy: 'N'
});

const { formRules, createConfirmPwdRule, createAgreePolicyRule } = useFormRules();
type RuleKey = keyof FormModel;

const rules: Record<RuleKey, CommonType.WithArray<App.Global.FormRule>> = {
  userPhone: formRules.phone,
  password: formRules.pwd,
  confirmPassword: createConfirmPwdRule(model.password),
  agreePolicy: createAgreePolicyRule()
};

async function handleSubmit() {
  await validate();
  setLoading(false);
}
</script>

<template>
  <div>
    <Title title="创建账号 🚀">
      <template #desc>
        <slot name="subTitle">让您的应用程序管理变得见简单而有趣</slot>
      </template>
    </Title>
    <NForm ref="formRef" :model="model" :rules="rules" size="large" :show-label="false" @keyup.enter="handleSubmit">
      <NFormItem path="userPhone">
        <NInput v-model:value="model.userPhone" placeholder="请输入手机号" />
      </NFormItem>
      <NFormItem path="password">
        <InputPassword v-model:value="model.password" show-password-on="click" placeholder="请输入密码" />
      </NFormItem>
      <NFormItem path="confirmPassword">
        <NInput v-model:value="model.confirmPassword" type="password" show-password-on="click" placeholder="确认密码" />
      </NFormItem>
      <NFormItem path="agreePolicy">
        <NCheckbox v-model:checked="model.agreePolicy" checked-value="Y" unchecked-value="N">我同意</NCheckbox>
        <NButton type="primary" text tag="a" class="text-sm font-normal">隐私政策 & 条款</NButton>
      </NFormItem>
      <NFormItem>
        <NButton type="primary" size="large" :loading="loading" round block @click="handleSubmit">注册</NButton>
      </NFormItem>
    </NForm>
    <div class="mt-4 text-center text-sm">
      已经有账号了？
      <NButton type="primary" text tag="a" class="text-sm font-normal" @click="emit('changeModule', 'pwd-login')">
        去登陆
      </NButton>
    </div>
  </div>
</template>

<style scoped></style>
